﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;

namespace doondo
{
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public string ConnectString()
        {
            string strConn;
            strConn = "Data Source=JESLYNN-PC\\SQLEXPRESS;Initial Catalog=searchDB;Integrated Security=True;";
            return strConn;
        }

        protected void btnButton_Click(object sender, EventArgs e)
        {
            try
            {
                string[] dirs = Directory.GetFiles(@tbxPath.Text, "*.txt");

                foreach (string dir in dirs)
                {
                    string textFile = dir;
                    string textBytes = null;
                    FileStream fs = new FileStream(textFile, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    textBytes = sr.ReadToEnd();
                    Check(textFile, textBytes);
                }
            }
            catch (DirectoryNotFoundException ex)
            {
                lblError.Text = "Invalid directory. Please input the correct one.";
            }
            

        }

        public void Check(string fileName, string fileContent)
        {
            string fileLink;
            string fileNameOnly;
            string fileDate;
            string fileSize;
            FileInfo fInfo = new FileInfo(fileName);
            fileDate = fInfo.LastWriteTime.ToString();
            fileSize = fInfo.Length.ToString() + " bytes";

            fileNameOnly = Path.GetFileName(fileName);
            fileLink = "file:\\\\\\" + fileName;

            if ((CheckFileName(fileName)) == true)
            {
                //Show the error message that record already exists.
                if ((CheckFileContent(fileContent)) == true)
                {
                    lblError.Text = "The files are already in Database. <br /> Click <a href='default.aspx'>here</a> to proceed to the search page<br />";
                }
                else if ((CheckFileContent(fileContent)) == false)
                {
                    SqlConnection conn = new SqlConnection();
                    SqlCommand comm = new SqlCommand();

                    try
                    {
                        conn.ConnectionString = ConnectString();
                        conn.Open();
                        comm.Connection = conn;
                        comm.CommandText = "UPDATE [searchDB].[dbo].[fileTable] SET fileContent='" + fileContent + "' WHERE fileName like '" + fileName + "'";
                        comm.ExecuteNonQuery();
                        comm.Parameters.Clear();
                        lblError.Text = "Files are updated into the database successfully. <br /> Click <a href='default.aspx'>here</a> to proceed to the search page";
                    }
                    catch (Exception ex)
                    {
                        lblError.Text = ex.Message;
                    }
                    finally
                    {
                        conn.Close();
                    }

                }

            }
            else if (CheckFileName(fileName) == false)
            {
                SqlConnection conn = new SqlConnection();
                SqlCommand comm = new SqlCommand();

                try
                {

                    conn.ConnectionString = ConnectString();
                    conn.Open();
                    comm.Connection = conn;
                    comm.CommandText = "INSERT INTO [searchDB].[dbo].[fileTable] VALUES ('" + fileName + "','" + fileContent + "','" + fileLink + "','" + fileNameOnly + "','" + fileSize + "','" + fileDate + "')";
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                    lblError.Text = "Files are saved into the database successfully. <br /> Click <a href='default.aspx'>here</a> to proceed to the search page";
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

        }

        private bool CheckFileName(string fName)
        {
            SqlConnection conn = new SqlConnection();
            SqlCommand comm = new SqlCommand();

            conn.ConnectionString = ConnectString();
            conn.Open();

            comm.Connection = conn;

            comm.CommandText = "SELECT fileName FROM [searchDB].[dbo].[fileTable] WHERE fileName like '" + fName + "'";

            comm.ExecuteNonQuery();

            SqlDataAdapter da = new SqlDataAdapter(comm);
            DataTable dt = new DataTable();
            da.Fill(dt);



            if (dt.Rows.Count > 0)
            {

                return true;
            }
            else
            {
                return false;

            }
        }

        private bool CheckFileContent(string fContent)
        {
            SqlConnection conn = new SqlConnection();
            SqlCommand comm = new SqlCommand();

            conn.ConnectionString = ConnectString();
            conn.Open();

            comm.Connection = conn;

            comm.CommandText = "SELECT fileName FROM [searchDB].[dbo].[fileTable] WHERE fileContent like '" + fContent + "'";

            comm.ExecuteNonQuery();

            SqlDataAdapter da = new SqlDataAdapter(comm);
            DataTable dt = new DataTable();
            da.Fill(dt);



            if (dt.Rows.Count > 0)
            {

                return true;
            }
            else
            {
                return false;

            }

        }
    }
}
